.module TileMap

	.tvar ubyte, BitplaneCount
	.tvar ubyte, Width
	.tvar ubyte, Height
	
	Load
	
		push bc
	
		xor a
		ld d,$40
		call Sprites.LoadDirect
		
		ld a,(hl) \ ld (Width),a \ inc hl
		ld a,(hl) \ ld (Height),a \ inc hl
		
		; Write the name table data
		
		pop bc
			
		push hl
		; b = x, c = y
		
		.if Config.Platform == Config.Platform.GG
			ld a,b \ add a,6 \ ld b,a
			ld a,c \ add a,3 \ ld c,a
		.endif
		
		ld l,c
		ld h,0
		
		add hl,hl
		add hl,hl
		add hl,hl
		add hl,hl
		add hl,hl
		add hl,hl
		
		sla b
		ld e,b
		ld d,0
		add hl,de		
		
		ld de,Video.NameTable
		add hl,de
		
		
		.tvar uword, RowStart
		ld (RowStart),hl
						
		call Video.GotoHL
						
		pop ix
	
		ld a,(Height)
		ld b,a
		
		ld hl,0; hl = tile index
		
	OutputRowLoop
		push bc
		
		ld a,(Width)
		ld b,a
		ld c,$BE
				
	
	RealTilesLoop		
		ld a,(ix) \ inc ix
		cp 127
		jr nz,NotFullValue
		
		ld l,(ix) \ inc ix
		ld h,(ix) \ inc ix
		
		
		jr LoadedFullValue
		
	NotFullValue
		ld e,a
		sla a
		sbc a,a
		ld d,a
		add hl,de
	LoadedFullValue
		
		out (c),l
		out (c),h
		
		djnz RealTilesLoop
		
		push hl
		ld hl,(RowStart)
		ld de,64
		add hl,de
		ld (RowStart),hl
		call Video.GotoHL
		pop hl
		
		
		pop bc
		djnz OutputRowLoop

		ret
.endmodule